import { ref} from 'vue'
import UserRanking from '@/types/UserRanking'
import request from '@/base/request'
import { ElMessage } from 'element-plus'
import router from '@/router'
import ProblemParm from '@/types/problemParm'
import {useproblemStore} from '@/stone/problem'
import JudgeResult from '@/types/judgeResult'
import ProblemRecord from '@/types/problemRecord'
import page from '@/base/page'
import Text from '@/types/text'
import TextRecord from '@/types/textRecord'
export default function () {

    interface Ranking {
        rankingScore: number,
        totalUser: number,
        ranking: number,
        loginUserRankingList?: Array<UserRanking> //该用户的分值变化情况集合
        allUserRankingList?: Array<UserRanking>//所有用户最后一次分值的排序集合，即排行榜
    }


    const testList=ref<Array<TextRecord>>()




    const problemRecord=ref<page<ProblemRecord>>({
        items:[],
        page:0,
        pageSize:0,
        counts:0
    })

    const problemRecordParm=ref({
        pageNo:1,
        pageSize:6,
        isRight:null,
        problemId:null,
        problemDescribe:null,
        userId:null,
    })

    const textParm=ref({
        textName:"",
        textId:"",
        status:"",
    })


    const isLoading=ref<boolean>(false)

    const right=ref(0);
    const wrong=ref(0);

    const showMessage = ref(false);  
    let animationTimeout; 

    const problemStore=useproblemStore()

    const input=ref()

    const inputMultiple=ref<Array<string>>([])

    

    const submitted=ref<boolean>(false)

    const judgeResult=ref<JudgeResult>()

    const submitParm={
        problemId:0,
        answer:""
    }

    const ranking = ref<Ranking>()

    async function getRanking(userId) {

        const response = await request.get(`/user/getRanking/${userId}`)
        if (response.data.code === 200) {
            ranking.value = response.data.data
            
        } else {
            ElMessage.error(`获取排名失败:${response.data.msg}`)
        }
    }

    async function submitAnswer(problemId:number,isMutiple:boolean) {
        if(isMutiple){
            let sortedString=Object.values(inputMultiple.value).sort((a,b)=>{return a.localeCompare(b)})
            input.value=sortedString.map(str=>str).join('')
        }
        submitParm.answer=input.value,
        submitParm.problemId=problemId
        isLoading.value=true;
        try{
            const response=await request.post("/judge/submitAnswer",submitParm)
            if(response.data.code===200){
                judgeResult.value=response.data.data
                if(judgeResult.value.isRight){
                    right.value++;
                }else{

                    wrong.value++;
                }
                showMessage.value = true;  
                submitted.value=true


                clearTimeout(animationTimeout);  
                animationTimeout = setTimeout(() => {  
                  showMessage.value = false;  
                }, 1000); 
            }else{
                ElMessage({
                    message:`提交失败：${response.data.msg}`,
                    grouping:true,
                    type:'error'
                })
            }
        }finally{
            isLoading.value=false
        }

    }


    async function getProblemRecord() {
        const response=(await request.post("/judge/getProblemRecord",problemRecordParm.value)).data
        if(response.code===200){
            problemRecord.value=response.data
        }else{
            ElMessage({
                message:`获取记录失败：${response.msg}`,
                grouping:true,
                type:'error'
            })
        }
    }

    async function getTextList(userId) {
        const response=(await request.get(`/problem/test/getTextList?textName=${textParm.value.textName}&textId=${textParm.value.textId}&status=${textParm.value.status}&userId=${userId}`)).data
        if(response.code===200){
            testList.value=response.data
        }else{
            ElMessage.error(`获取测验记录失败，${response.msg}`)
        }
    }

    async function reSubmit(textId:number) {

       const response=(await (request.get(`/problem/test/reSubmit/${textId}`))).data
       if(response.code===200){
            ElMessage.success("提交成功，请稍等片刻后刷新界面查看重测结果")

       }else{
            ElMessage.error(`重测失败：${response.msg}`)
       }
    }

    function toStartTest(){
        router.push('/test/startTest')
    }

    function toStartProblem(problemParm:ProblemParm){
        problemStore.problemParm=problemParm
        router.push('/test/startProblem')
    }

    function handlePageChange(newPage:number){
        problemRecordParm.value.pageNo=newPage
        getProblemRecord()
    }

    const getTableRowClassName = ({
        row,
        rowIndex,
    }: {
        row: ProblemRecord
        rowIndex: number
    }) => {
        if (!row.result) {
            return 'wrong-row'
        } else {
            return 'right-row'
        }
    }



    return {problemRecord,problemRecordParm,showMessage,isLoading,judgeResult,right,wrong,submitted,input, ranking,testList,textParm,inputMultiple
        ,reSubmit,getTextList,getTableRowClassName,handlePageChange,getProblemRecord, getRanking,toStartTest,toStartProblem,submitAnswer}
}